<%@ tag pageEncoding="UTF-8" %>
<!-- Spring 的分页对象 -->
<%@ attribute name="page" type="org.springframework.data.domain.Page" required="true" %>
<!-- 分页控件显示的数量 -->
<%@ attribute name="paginationSize" type="java.lang.Integer" required="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%
  int current = page.getNumber() + 1;
  int begin = Math.max(1, current - paginationSize / 2);
  int end = Math.min(begin + (paginationSize - 1), page.getTotalPages());

  request.setAttribute("current", current);
  request.setAttribute("begin", begin);
  request.setAttribute("end", end);
  request.setAttribute("totalPage", page.getTotalPages());

  request.setAttribute("hasPrevious", page.hasPrevious());
  request.setAttribute("hasNext", page.hasNext());
%>


<div class="form-inline">
  <div class="form-group">
    <div class="btn-group btn-group-sm open" style="float: none;">

      <c:if test="${hasPrevious}">
        <a class="btn btn-default" href="?page=1&sortType=${sortType}&${searchParams}">&lt;&lt;</a>
      </c:if>

      <c:forEach var="i" begin="${begin}" end="${end}">
        <c:choose>
          <c:when test="${i == current}">
            <a class="btn btn-default active" href="?page=${i}&sortType=${sortType}&${searchParams}">${i}</a>
          </c:when>
          <c:otherwise>
            <a class="btn btn-default" href="?page=${i}&sortType=${sortType}&${searchParams}">${i}</a>
          </c:otherwise>
        </c:choose>
      </c:forEach>

      <c:if test="${hasNext}">
        <a class="btn btn-default" href="?page=${page.totalPages}&sortType=${sortType}&${searchParams}">&gt;&gt;</a>
      </c:if>

    </div>
  </div>

  <!-- 页面跳转 -->
  <c:if test="${totalPage > paginationSize}">
    <div class="form-group">
      <div class="hidden-xs">
        <input class="form-control input-sm" id="skip-btn" type="text" style="width: 45px;" value="${current}">
        <button class="btn btn-sm btn-default" onclick="pageSkip()">跳转</button>
        </li>
      </div>
    </div>
  </c:if>

</div>

<script>
  function pageSkip() {
    var pageVal = $("#skip-btn").val();
    if (!isNumber(pageVal)) {
      alert("‘跳转页数’请填写数值！");
      $("#skip-btn").val("${current}");
      $("#skip-btn").focus();
    } else {
      //超出范围的，分别取最大和最小值.
      if (pageVal > "${totalPage}") {
        pageVal = "${totalPage}"
      }

      if (pageVal < 1) {
        pageVal = 1;
      }
      window.location.href = "?page=" + pageVal + "&sortType=${sortType}&${searchParams}";
    }
  }

  function isNumber(oNum) {
    if (!oNum) return false;
    /* var strP = /^\d+(\.\d+)?$/; 带小数点*/
    var strP = /^\d+(\d+)?$/;
    if (!strP.test(oNum)) return false;
    try {
      if (parseFloat(oNum) != oNum) return false;
    }
    catch (ex) {
      return false;
    }
    return true;
  }
</script>
